using AutoMapper;
using B.S.BaseData.Api.Read.Command.OrderCommand;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using WorkOrder.Domain;
using WorkOrder.Domain.DTOs;


namespace B.S.BaseData.Api.Read.CommandHandler.OrderCommandHandler
{
    /// <summary>
    /// 获取药品订单详情处理器
    /// </summary>
    public class GetMedicineOrderDetailHandler : IRequestHandler<GetMedicineOrderDetailCommand, APIResult<MedicineOrderDto>>
    {
        private readonly BaseDbContext _dbContext;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        /// <param name="mapper">对象映射器</param>
        public GetMedicineOrderDetailHandler(BaseDbContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取药品订单详情命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>订单详情</returns>
        public async Task<APIResult<MedicineOrderDto>> Handle(GetMedicineOrderDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询药品订单及其明细
                var order = await _dbContext.Set<MedicineOrder>()
                    .Include(o => o.Items)
                    .FirstOrDefaultAsync(o => o.OrderNumber == request.OrderNumber, cancellationToken);

                if (order == null)
                {
                    return new APIResult<MedicineOrderDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的药品订单",
                        Data = null
                    };
                }

                // 映射到DTO
                var orderDto = _mapper.Map<MedicineOrderDto>(order);

                return new APIResult<MedicineOrderDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取成功",
                    Data = orderDto
                };
            }
            catch (Exception ex)
            {
                return new APIResult<MedicineOrderDto>
                {
                    Code = ApiEnum.Fail,
                    Msg = ex.Message,
                    Data = null
                };
            }
        }
    }

    /// <summary>
    /// 获取物流详情处理器
    /// </summary>
    public class GetLogisticsDetailHandler : IRequestHandler<GetLogisticsDetailCommand, APIResult<LogisticsDetailDto>>
    {
        private readonly BaseDbContext _dbContext;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        /// <param name="mapper">对象映射器</param>
        public GetLogisticsDetailHandler(BaseDbContext dbContext, IMapper mapper)
        {
            _dbContext = dbContext;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理获取物流详情命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>物流详情</returns>
        public async Task<APIResult<LogisticsDetailDto>> Handle(GetLogisticsDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查询药品订单
                var order = await _dbContext.Set<MedicineOrder>()
                    .FirstOrDefaultAsync(o => o.OrderNumber == request.OrderNumber, cancellationToken);

                if (order == null)
                {
                    return new APIResult<LogisticsDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "未找到指定的药品订单",
                        Data = null
                    };
                }

                // 检查订单是否有物流信息
                if (string.IsNullOrEmpty(order.LogisticsCompany) || string.IsNullOrEmpty(order.TrackingNumber))
                {
                    return new APIResult<LogisticsDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "该订单暂无物流信息",
                        Data = null
                    };
                }

                // 构建物流详情（这里模拟物流数据，实际项目中应该调用第三方物流API）
                var logisticsDetail = new LogisticsDetailDto
                {
                    OrderNumber = order.OrderNumber,
                    LogisticsCompany = order.LogisticsCompany,
                    TrackingNumber = order.TrackingNumber,
                    StatusList = GenerateMockLogisticsStatus(order.CreateTime, order.UpdateTime ?? order.CreateTime)
                };
                return new APIResult<LogisticsDetailDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "未找到指定的药品订单",
                    Data = logisticsDetail
                };
            }
            catch (Exception ex)
            {
                return new APIResult<LogisticsDetailDto>
                {
                    Code = ApiEnum.Fail,
                    Msg = ex.Message,
                    Data = null
                };
            }
        }

        /// <summary>
        /// 生成模拟物流状态数据
        /// </summary>
        /// <param name="createTime">创建时间</param>
        /// <param name="updateTime">更新时间</param>
        /// <returns>物流状态列表</returns>
        private List<LogisticsStatusDto> GenerateMockLogisticsStatus(DateTime createTime, DateTime updateTime)
        {
            var statusList = new List<LogisticsStatusDto>();
            
            // 根据图片中的物流状态生成模拟数据
            var baseTime = createTime;
            
            // 订单开始处理
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddHours(-1),
                Status = "订单开始处理",
                Description = "",
                IsLatest = false
            });

            // 已发货
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddHours(-1).AddMinutes(30),
                Status = "已发货",
                Description = "卖家已发货",
                IsLatest = false
            });

            // 已揽件
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddHours(-1).AddMinutes(45),
                Status = "已揽件",
                Description = "包裹正在揽收",
                IsLatest = false
            });

            // 快件在【华北陆运枢纽(天津)】已装车
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddDays(1),
                Status = "快件在【华北陆运枢纽(天津)】已装车; 准备发往【北京顺义集散中心】",
                Description = "",
                IsLatest = false
            });

            // 快件到达【北京顺义集散中心】
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddDays(3),
                Status = "快件到达【北京顺义集散中心】",
                Description = "",
                IsLatest = false
            });

            // 快件到达【北京朝阳区营业部】
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddDays(5),
                Status = "快件到达【北京朝阳区营业部】",
                Description = "",
                IsLatest = false
            });

            // 派送中（最新状态）
            statusList.Add(new LogisticsStatusDto
            {
                Time = baseTime.AddDays(5).AddHours(3),
                Status = "派送中",
                Description = "德邦快递员正在配送,请耐心等待",
                IsLatest = true
            });

            // 按时间倒序排列（最新的在前面）
            return statusList.OrderByDescending(x => x.Time).ToList();
        }
    }
} 